package com.name.givename.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.name.givename.dao.UserNamedInfoEntityMapper;
import com.name.givename.dto.GiveNameHistoryDTO;
import com.name.givename.dto.NameListDTO;
import com.name.givename.entity.UserNamedInfoEntity;
import com.name.givename.enums.ResultEnum;
import com.name.givename.exception.ServiceException;
import com.name.givename.param.PageParams;
import com.name.givename.param.UserNameInfoParams;
import com.name.givename.param.UserOpenRedpackParams;
import com.name.givename.result.ResultVoUtils;
import com.name.givename.service.UserNameInfoService;
import com.name.givename.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/userNameInfo")
@Api("用户起名中心")
public class UserNameInfoController {

    @Autowired private UserNameInfoService userNameInfoService; // 用户起名服务
    @Autowired private UserNamedInfoEntityMapper userNamedInfoEntityMapper;

    @ApiOperation("用户全部起名信息")
    @PostMapping("/getUserNameInfos")
    public Result<Page<NameListDTO>> getUserNameInfos(@RequestBody PageParams pageParams){
        //  pageParams 设置了默认参数 但是不好使 故在此显示设置
        PageHelper.startPage(pageParams.getPageNumber() == null ? 1 : pageParams.getPageNumber(),pageParams.getPageSize() == null ? 10 : pageParams.getPageSize());
        List<NameListDTO> list =  userNameInfoService.getUserNameInfo(pageParams);
        if (pageParams.getOrderId() == 1) {
            // 默认按照升序 排序
            Collections.sort(list,Comparator.comparing(NameListDTO::getVote_count));
        }
        PageInfo pageInfo =new PageInfo(list);
        return ResultVoUtils.success(pageInfo);
    }

    @ApiOperation("首页搜索用户起名信息")
    @PostMapping("/selectUserNameInfo")
    public Result<List<UserNamedInfoEntity>> getUserNameInfoByIdOrName(@RequestBody UserNameInfoParams userNameInfoParams){
        if(null == userNameInfoParams.getGiveName()){
            return null;
        }
        return ResultVoUtils.success(userNameInfoService.getUserNameInfoByIdOrName(userNameInfoParams.getGiveName()));
    }

    @ApiOperation("获取用户历史起名记录")
    @PostMapping("/getUserNameHistory")
    public Result<GiveNameHistoryDTO>getUserNameHistory(@RequestBody UserOpenRedpackParams userOpenRedpackParams) {
        return ResultVoUtils.success(userNamedInfoEntityMapper.getUserAddNameList(userOpenRedpackParams.getOpenId()));
    }


}
